package com.rimi.shiro;

import com.rimi.bean.YqzcUser;
import com.rimi.service.UserService;
import com.rimi.util.PwdUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @Author luc
 * @Date 2021/6/30
 */

public class MysqlRealm extends AuthorizingRealm {

    @Autowired
     UserService userService;

    /**
     *   如何进行权限校验
     * @param principals    在身份认证时，交给shiro会话管理的对象
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {


        return null;
    }

    /**
     *  如何进行身份认证
     * @param token   用户输入的用户名密码组合而成的token
     *
     *                1. 获取用户输入的用户名
     *                2. 根据用户名查询数据库有无当前用户
     *                3. 获取用户输入的密码
     *                4. 将数据库查询得到的密码和用户输入的密码进行比较(可能存在加密比较)
     *                5. 如果比较相等，则将用户信息写入shiro 会话管理
     *                6. 如果比较失败，则返回异常
     *
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
       String userPhoneNumber=(String) token.getPrincipal();

        YqzcUser yqzcUser=userService.findUserByUserPhoneNumber(userPhoneNumber);

        return new SimpleAuthenticationInfo(yqzcUser,yqzcUser.getUserPassword(), PwdUtil.salt(),getName());
    }
}
